package org.jz.gae.redbook.spb.client.slate.location;

import org.jz.gae.redbook.spb.client.toolkit.Slate;
import org.jz.gae.redbook.spb.shared.LocationEntityView;
import org.jz.gae.redbook.spb.shared.MapHelper;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.maps.client.MapType;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.control.LargeMapControl;
import com.google.gwt.maps.client.event.MarkerDragEndHandler;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.maps.client.overlay.MarkerOptions;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class LocationEditPlate extends Composite
{
      private VerticalPanel rootPanel = new VerticalPanel();
	  private final Button saveButton = new Button("Сохранить");
	  private final Button cancelButton = new Button("Отмена");;
	  private LocationPropertiesPanel locationPropertiesPanel = new LocationPropertiesPanel();
	  private Slate slate;
	  private ClickHandler submitEvent; 
      private LocationEntityView entityView;
	  private MapWidget mapPanel;

	public LocationEditPlate() 
	{
		SimplePanel contentTableDecorator = new SimplePanel();
	  initWidget(contentTableDecorator);
	  contentTableDecorator.setWidth("100%");
	  initilizeInterface();
      contentTableDecorator.add(rootPanel);
      
      saveButton.addClickHandler(new ClickHandler(){
    	  @Override
    	  public void onClick(ClickEvent event)
          {
              submitOperation();
    	  }
      });
      cancelButton.addClickHandler(new ClickHandler(){
    	  @Override
    	  public void onClick(ClickEvent event)
          {
              cancelOperation();
    	  }
      });
	}

	private void initilizeInterface()
	{
		rootPanel.setWidth("100%");
		locationPropertiesPanel.setWidth("100%");
		rootPanel.add(locationPropertiesPanel);
	    HorizontalPanel menuPanel = new HorizontalPanel();
	    menuPanel.add(saveButton);
	    menuPanel.add(cancelButton);
	    rootPanel.add(menuPanel);
	    /**/
	    LatLng mapCenter = LatLng.newInstance(MapHelper.MAP_CENTER_LAT, MapHelper.MAP_CENTER_LONG);
	    int mapZoomLevel = MapHelper.MAP_ZOOM_LEVEL;
	    mapPanel = new MapWidget(mapCenter, mapZoomLevel);
	    mapPanel.setCenter(mapCenter, mapZoomLevel, MapType.getNormalMap());
		mapPanel.setWidth("100%");
		mapPanel.setHeight("50em");
		mapPanel.addControl(new LargeMapControl());
	    rootPanel.add(mapPanel);
	}

	public void editEntityView(
			Slate _Slate,
		    String _LocationId,	
			ClickHandler _SubmitEvent)
	{
		slate = _Slate;
		slate.getContainerAgent().getRpcService().getLocation(_LocationId, new AsyncCallback<LocationEntityView>(){
			@Override
			public void onFailure(Throwable caught)
			{
				Window.alert("Ошибка загрузки семейства : " + caught.getMessage());
			}

			@Override
			public void onSuccess(LocationEntityView result)
			{
				entityView = result;
				locationPropertiesPanel.displayInformation(entityView);
				locationPropertiesPanel.setSlate(slate);
				LatLng locationPont = LatLng.newInstance(entityView.getLocationCoordLatitude(), entityView.getLocationCoordLongitude());
				MarkerOptions locationOptions =  MarkerOptions.newInstance();
				locationOptions.setDraggable(true);
				final Marker locationMarker = new Marker(locationPont, locationOptions);
				locationMarker.addMarkerDragEndHandler(new MarkerDragEndHandler()
				{
					@Override
					public void onDragEnd(MarkerDragEndEvent event)
					{
						locationPropertiesPanel.setLocationCoords(event.getSender().getLatLng());
					}
				});
				mapPanel.addOverlay(locationMarker);
				locationPropertiesPanel.setLocationCoordChangeListener(new LocationPropertiesPanel.LocationCoordChangeListener()
				{
					@Override
					public void locationCoordsChanged(
							double _Latitude, 
							double _Longitude)
					{
						locationMarker.setLatLng(LatLng.newInstance(_Latitude, _Longitude));
			        }
				});
			}
		});
		submitEvent = _SubmitEvent;
		slate.exposePlate(this);
	}
	
	private void cancelOperation()
	{
		slate.closeTopPlate();
	}
	
	private void submitOperation()
	{
		try
		{
			LocationEntityView locationEntityView = locationPropertiesPanel.pickUpInformation();
			if (
					(locationEntityView.getLocationDistrictKey() == null)
		            ||
					(locationEntityView.getLocationDistrictKey().equals(""))
			   )
			{
				throw new Exception("Необходимо выбрать район");
			}
			if (
					(locationEntityView.getLocationSpeciesKey() == null)
		            ||
					(locationEntityView.getLocationSpeciesKey().equals(""))
			   )
			{
				throw new Exception("Необходимо выбрать вид");
			}
			locationEntityView.setLocationKey(entityView.getLocationKey());
		    slate.getContainerAgent().getRpcService().updateLocation(
		    		locationEntityView, 
		    		new AsyncCallback<LocationEntityView>() {
				        public void onSuccess(LocationEntityView result) 
				        {
				            slate.closeTopPlate();
				            submitEvent.onClick(new ClickEvent(){});
				        }
				        public void onFailure(Throwable caught) 
				        {
				             Window.alert("Error updating location");
				        }
				    });
		}
		catch(Exception ex)
		{
            Window.alert("Invalid data : " + ex.getMessage());
		}
		
	}
}